// default expire time
const DEFAULT_CACHE_TIME = 60 * 60 * 24 * 7

/*
* @description create localStorage Object
* @param prefixKey
* @param Object
* */
export const createStorage = ({ prefixKey = '', storage = localStorage } = {}) => {
  /*
  * @description localStorage class
  * @class Storage
  * */
  const Storage = class {
    private storage = storage
    private prefixKey?: string = prefixKey

    private getKey (key: string) {
      // upperCase key
      return `${this.prefixKey}${key}`.toUpperCase()
    }

    /*
    * @description set localStorage
    * @param key
    * @param value
    * @param expire
    * */
    set (key: string, value: any, expire: number | null) {
      const stringData = JSON.stringify({
        value,
        expire: expire !== null ? new Date().getTime() + expire * 1000 : null
      })
      this.storage.setItem(this.getKey(key), stringData)
    }

    /*
    * @description get localStorage
    * @param key
    * @param def default value
    * */
    get (key: string, def: any = null) {
      const item = this.storage.getItem(this.getKey(key))
      if (item) {
        try {
          const data = JSON.parse(item)
          const { value, expire } = data
          // return value when the time in expire
          if (expire === null || expire >= Date.now()) {
            return value
          }
          this.remove(key)
        } catch (e) {
          return def
        }
      }
      return def
    }

    /*
    * @description remove the key localStorage
    * @param key
    * */
    remove (key: string) {
      this.storage.removeItem(this.getKey(key))
    }

    /*
    * @description clear all localStorage
    * */
    clear () {
      this.storage.clear()
    }
  }
  return new Storage()
}

export const storage = createStorage()

export default storage
